from django.shortcuts import render, render_to_response
from django.http import HttpResponse
from LR.models import Data
import hashlib

def login(request):
    if request.method == "POST":
            # 获取表单信息
        username = request.POST.get('dID')
        password = request.POST.get('dPW')
        userResult = Data.objects.filter(username=username, password=password)
        # pdb.set_trace()

        # assert False    取不到password 和 username
        if len(userResult) > 0:
            return HttpResponse("登录成功！")
        else:
            return HttpResponse("用户不存在")

    return render(request, 'login.html', {})


def register(request):
    if request.method == "POST":

        # 获取表单信息
        username = request.POST.get('dID')
        # pdb.set_trace()

        # try:
        filterResult = Data.objects.filter(username=username)
        if len(filterResult) > 0:
            return render_to_response('register.html', {"errors": "用户名已存在"})
        else:
            password1 = request.POST.get('PW')
            password2 = request.POST.get('PW2')
            errors = []
            if password2 != password1:
                errors.append("两次输入的密码不一致!")
                return render_to_response('register.html', {'errors': errors})
                # return HttpResponse('两次输入的密码不一致!,请重新输入密码')
            password = password2
            email = request.POST.get('MAIL')

            #使用md5算法，单向加密用户密码
            md5 = hashlib.md5()
            c = password.encode("utf-8")
            #hash前需要编码
            md5.update(c)
            password = md5.hexdigest()

            # 将表单写入数据库
            user = Data(username=username, password=password, email=email)
            # user = User(username=username,password=password,email=email)
            user.save()
            # 返回注册成功页面
            return HttpResponse("注册成功！")

    return render(request, 'register.html', {})


